/**
MonthReportItemRowWatcher.java
business
2012-8-1下午5:06:31
@author 屈甲康
@QQ285799123
mailto:qujiakang@126.com
**/
package org.jackysoft.report.rows;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.jackysoft.entity.Department;
import org.jackysoft.service.DepartmentService;
import org.jackysoft.util.AbstractRowWatcher;
import org.jackysoft.util.ExcelUtil;

import com.google.common.collect.Maps;

/**
 * 导入月报excel行解析器
 * */
public class ArmItemMonthlyReportRowWatcher extends AbstractRowWatcher {
	
	private Log logger = LogFactory.getLog(ArmItemMonthlyReportRowWatcher.class);
	private Map<String, Map<String,Double[]>> mps;
	private DepartmentService deptService;
	
	private Map<String,Double[]> values = null;
	private int lineNumber;
	
	
	public ArmItemMonthlyReportRowWatcher(
			Map<String, 
			Map<String,Double[]>> mps,
			DepartmentService deptService
			) {
		super();
		this.mps = mps;	
		this.deptService = deptService;
	}
	public ArmItemMonthlyReportRowWatcher(
			Map<String, Map<String,Double[]>> mps,
			String sheetkey,
			DepartmentService deptService) {
		super();
		this.mps = mps;		
		this.setSheetKey(sheetkey);
		this.deptService = deptService;
	}




	@Override
	public void accept(Row row) {
		lineNumber++;
		Iterator<Cell> cells = row.cellIterator();
		Cell codeName = ExcelUtil.nextCell(cells);
		String cellString = ExcelUtil.cellString(codeName);
		if(cellString.startsWith("#")){
			logger.warn(appendError("行 %d 已被忽略",lineNumber));
			return;
		}
		
		
		Department dept = deptService.getByName(getSheetKey());
		String deptId = dept.getId();
		if(deptId==null){
		    logger.error(appendError("部门标识 %s 不合法 行:%d", getSheetKey(),lineNumber));
		    
		    return;
		}
		values = mps.get(deptId);
		if(values==null){
			values = Maps.newHashMap();
			mps.put(deptId, values);
		}
		
		
		String[] cns = cellString.split("\\s+");
		Double[] dvals = null;
		if(cns!=null && cns.length>0){
			String code = StringUtils.trim(cns[0]);
			dvals = values.get(code);
			if(dvals==null){
				dvals = new Double[2];
				values.put(code, dvals);	
			}
		}else{
			logger.error(appendError("代码名称列至少要有内容行:%d ",lineNumber));
			return ;
		}
		//忽略单位列
		ExcelUtil.nextCell(cells);
		
		//年初
		Cell year = ExcelUtil.nextCell(cells);
		Double yval = ExcelUtil.cellNumber(year);
		dvals[0] = yval;
		
		//月初
		Cell month = ExcelUtil.nextCell(cells);
		Double mval = ExcelUtil.cellNumber(month);
		dvals[1] = mval;
		//logger.debug("解析了产品\t部门: "+deptId +"\t代码: "+cns[0]+"\t年初: "+yval+",\t月初: "+mval);
		
	}

}
